import { read as readApi } from '@/services/system/upload';
import { UploadOutlined } from '@ant-design/icons';
import { Button, notification, Upload } from 'antd';
import { useEffect, useState } from 'react';
import fileImg from '@/assets/images/file.png';
import { upload } from '@/utils/tools/file';
import {API_URL, IMG_URL, NORMAL_CODE} from '@/constants';

const CustomUpload: React.FC = (props) => {
  const imgList = ['jpg', 'jpeg', 'png'];

  const [fileList, setFileList] = useState([]);
  useEffect(() => {
    let abortController = new AbortController();
    const asyncFn = async () => {
      //fileList改造
      const imgs = props.value === 0 ? '' : props.value.toString();
      let files = imgs
          .split(',')
          .filter((i) => i && i.trim())
          .map(async (fileId) => {
            const res = await readApi({ id: fileId });
            let thumbUrl = IMG_URL + fileId;
            if (imgList.indexOf(res.data.ext) < 0) {
              thumbUrl = fileImg;
            }
            return {
              uid: fileId,
              name: res.data.name,
              ext: res.data.ext,
              status: 'done',
              value: fileId,
              url: IMG_URL + fileId,
              thumbUrl: thumbUrl,
            };
          });
      // 使用Promise.all进行请求
      if(files.length > 0){
        files = await Promise.all(files);
      }
      setFileList(files);
    };
    asyncFn();
    return () => {
      abortController.abort();
    };

  }, [props.value]);
  //上传参数
  let uploadProps = {
    accept: props.accept || '.jpg', //接受上传的文件类型
    // defaultFileList: props.defaultFileList || [], //默认已经上传的文件列表
    fileList: fileList, //已经上传的文件列表
    data: props.data || {}, //上传所需额外参数或返回上传额外参数的方法
    directory: props.directory || false, //支持上传文件夹
    disabled: props.disabled || false, //是否禁用
    listType: props.listType || 'picture', //上传列表的内建样式，支持三种基本样式 text, picture 和 picture-card
    maxCount: props.maxCount || 1, //限制上传数量。当为 1 时，始终用最新上传的文件代替当前文件
    multiple: props.multiple || false, //是否支持多选文件，ie10+ 支持。开启后按住 ctrl 可选择多个文件
    showUploadList: props.showUploadList || true, //是否展示文件列表
    beforeUpload(file, fileList) {
      return true;
    },
    onStart(file) {},
    //放开导致自定义上传卡在进度条那
    // onSuccess(res, file) {
    // },
    onError(err) {
      notification['error']({
        message: '上传失败',
        description: '上传失败',
      });
    },
    onChange(info) {
      //受控更新
      setFileList(info.fileList);
      //通知父组件
      let fileIds = '';
      info.fileList.forEach((item) => {
        if (item.status === 'done') {
          fileIds = fileIds + (fileIds.length == 0 ? '' : ',') + item.value;
        }
      });
      props.onChange(fileIds);
    },
    async customRequest({ data, file, filename, onError, onProgress, onSuccess }) {
      const res = await upload({ data, file, filename, onProgress });
      if (res.code !== NORMAL_CODE) {
        return onError(res.msg);
      }
      //赋值，onChange那边能接收到
      file.value = res.data.id;
      file.url = IMG_URL + res.data.id;
      file.ext = res.data.ext;
      let thumbUrl = IMG_URL + res.data.id;
      if (imgList.indexOf(res.data.ext) < 0) {
        thumbUrl = fileImg;
      }
      file.thumbUrl = thumbUrl;
      onSuccess(res, file);
      return {
        abort() {
          console.log('upload progress is aborted.');
        },
      };
    },
  };

  const uploadButton = <Button icon={<UploadOutlined />}>上传</Button>;
  return <Upload {...uploadProps}>{uploadButton}</Upload>;
};

export default CustomUpload;
